from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):

    """
    Returns the response data for both the login and refresh views.
    Override to return a custom response such as including the
    serialized representation of the User.

    Example:

    def jwt_response_payload_handler(token, user=None, request=None):
        return {
            'token': token,
            'user': UserSerializer(user, context={'request': request}).data
        }
     obtain_jwt_token视图默认只返回了 token，自己添加多返回两个字段
    """
    return {
        'user_id': user.id,
        'username': user.username,
        'token': token
    }


class UsernameMobileAuthBackend(ModelBackend):
    """自定义登录方式，添加手机号码登录"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        query_set = User.objects.filter(Q(username=username) | Q(mobile=username))
        try:
            if query_set.exists():
                user = query_set.get()  # 取出唯一的一条数据（取不到或者有多条数据都会出错）
                if user.check_password(password):
                    return user
        except:
            return None
